/**
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */
package mobcam;

import java.io.IOException;
import java.io.PrintStream;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.lcdui.StringItem;

/**
 *
 * @author Knut Magne Solem
 */
public class ImageUploader {
    private String url;
    private StringItem statusField;

    public ImageUploader(String url, StringItem statusField) {
        this.url = url;
        this.statusField = statusField;
    }
    
    public boolean httpUpload(byte[] buf) {
        if (1 > buf.length) {
            return false;
        }

        HttpConnection conn = null;
        PrintStream output = null;
        int i = 0;
        
        try {
            conn = (HttpConnection) Connector.open(url, Connector.WRITE, true);
            conn.setRequestMethod(HttpConnection.POST);
            conn.setRequestProperty("Connection", "close");
            conn.setRequestProperty("Content-Type", "image/jpeg");
            output = new PrintStream(conn.openOutputStream());
            updateStatus("Writing data");
            int chunk = 512;
            do {
                int length = buf.length < chunk + i ? buf.length - i : chunk;
                output.write(buf, i, length);
                i += chunk;
                updateStatus("i: " + i + "/" + buf.length);
            } while (i < buf.length);
            updateStatus("Sent: " + buf.length + " freemem: " + Runtime.getRuntime().freeMemory());
        } catch (IOException e) {
            updateStatus("i" + i + "l:" + buf.length + "Exception:" + e.toString());
        } finally {
            try {
                output.close();
            } catch (Exception e) {
            }
            try {
                conn.close();
            } catch (Exception e) {
            }
        }
        return true;
    }

    private void updateStatus(String string) {
        statusField.setText(" " + string);
    }
  
}
